package com.ohuang.test_compose.page

import android.annotation.SuppressLint
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Tab
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.InternalComposeApi
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.currentComposer
import androidx.compose.ui.Modifier
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.pagerTabIndicatorOffset
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 *   需要的库
 *   implementation "com.google.accompanist:accompanist-pager:0.22.0-rc"
 *   implementation "com.google.accompanist:accompanist-pager-indicators:0.22.0-rc"
 */
@OptIn(ExperimentalPagerApi::class)
@InternalComposeApi
@ExperimentalAnimationApi
@SuppressLint("CoroutineCreationDuringComposition")

@Composable
fun TestHorizontalPager() {
    val pageSate = rememberPagerState()
    val pages = arrayListOf("TextPage", "CanvasPage", "CustomLayoutPage", "ImagePage")
    Column() {
        //获取协程上下文
        val applyContext = currentComposer.applyCoroutineContext
        //可使用  ScrollableTabRow  or TabRow
        ScrollableTabRow(
            // Our selected tab is our current page
            selectedTabIndex = pageSate.currentPage,
            // Override the indicator, using the provided pagerTabIndicatorOffset modifier
            indicator = { tabPositions ->
                TabRowDefaults.Indicator(

                    Modifier.pagerTabIndicatorOffset(pageSate, tabPositions)
                )
            }

        ) {
            // Add tabs for all of our pages
            pages.forEachIndexed { index, title ->
                Tab(
                    text = { Text(title, maxLines = 1)},
                    selected = pageSate.currentPage == index,
                    onClick = {
                        CoroutineScope(applyContext).launch {
                            pageSate.scrollToPage(page = index)
                        }
                    },
                )
            }
        }

        HorizontalPager(count = 4, state = pageSate) { page ->
            when (page) {
                0 -> TextPage()
                1 -> CanvasPage()
                2 -> CustomLayoutPage()
                3 -> ImagePage()
            }
        }

        LaunchedEffect(key1 = "1", block ={
               pageSate.scrollToPage(1)
        } )

    }
}